// logs.js
const util = require('../../utils/util.js')
const App = getApp()
const config = require('../../utils/config.js')
import Toast from 'tdesign-miniprogram/toast/index'
Page({
  data: {
    nickName: '',
    avatarUrl: null,
    mobile: null,
    apiUrl: util.apiUrl,
    staticUrl: App.globalData.img_path,
    imgs: [],
    count: 3,
    userInfo: {},
    isShowquan: false, // 微信授权 true:成功;false:失败
    openId: '',
    code: '',
    token: '',
    loginType: 'phone',
    argee: false
  },
  onLoad() {},
  // 跳转首页
  onGoHome: util.onGoHome,
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let nameInfoObject = wx.getStorageSync('nameInfoObject')
    if (nameInfoObject) {
      that.setData({
        nickName: nameInfoObject.nickName,
        avatarUrl: nameInfoObject.avatarUrl,
        mobile: nameInfoObject.mobile
      })
    }

    wx.login({
      success: (res) => {
        that.setData({
          code: res.code
        })
      }
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      avatarUrl
    })
  },

  canleAvatr() {
    this.setData({
      avatarUrl: null,
      nickName: null
    })
    wx.switchTab({
      url: '/pages/my/my'
    })
  },
  confimAvatr() {
    if (!this.data.avatarUrl)
      return Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择头像',
        theme: 'warning',
        direction: 'column'
      })
    if (!this.data.nickName)
      return Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入昵称',
        theme: 'warning',
        direction: 'column'
      })
    this.getLoginUserInfo(this.data.avatarUrl, this.data.nickName)
  },
  // 微信授权登录
  getLoginUserInfo(avatarUrl, nickName) {
    var that = this
    let nameInfoObject = {
      nickName,
      avatarUrl
    }

    wx.getUserProfile({
      desc: '必须授权才可以继续使用',
      success: (res) => {
        console.log('必须授权才可以继续使用', res)
        const userInfo = res.userInfo
        userInfo.nickName = nickName
        userInfo.avatarUrl = avatarUrl

        this.setData({ userInfo })
        // 获取code
        //发起网络请求
        wx.request({
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          url: this.data.apiUrl + '/api/login/codeGetOpenid',
          data: {
            code: this.data.code,
            nickname: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            city: userInfo.city,
            country: userInfo.country,
            invite: res.iv
          },
          dataType: 'json',
          success: function (response) {
            var res = response.data
            if (res.code == 0) {
              console.log(res)
              //可以把token和用户信息保存到本地缓存，前后端携带token交互
              // 把用户信息缓存到本地
              nameInfoObject.mobile = util.encryptPhoneNumber(res.data.mobile)
              wx.setStorageSync('openid', res.data.openid)
              wx.setStorageSync('user', userInfo)
              wx.setStorageSync('nameInfoObject', nameInfoObject)
              wx.setStorageSync('token', res.data.token)
              wx.setStorageSync('member_invite', res.data.member_invite)
              that.setData({
                token: res.data.token
              })

              that.getAddressList()

              // 信息存储完成后返回我的页面
              wx.switchTab({
                url: '/pages/home/index',
                success: function (e) {
                  const page = getCurrentPages().pop()
                  console.log(page)
                  if (page == undefined || page == null) return
                  page.onLoad()
                  page.onReady()
                }
              })

              if (res.data.member_tel == '') {
                that.setData({
                  isShowquan: true
                })
              } else {
                wx.redirectTo({
                  url: '../home/index'
                })
              }
            } else {
              wx.showToast({
                title: '登录失败',
                icon: 'error',
                duration: 1000
              })
              that.setData({
                isShowquan: false
              })
            }
          }
        })
      },
      fail: (res) => {
        console.log('授权失败', res)
      }
    })
  },

  getAddressList(e) {
    try {
      util.request('/api/address/index', {}, 'GET').then((res) => {
        var datas = res.data
        if (datas.code == 0) {
          let position = datas.data.find((item) => item.is_default === 1)
          if (!position) position = datas.data[0]

          wx.setStorageSync('position', position)
          console.log('position设置成功')
        } else {
          console.log('地址获取失败')
        }
      })
    } catch (err) {
      console.log(err)
    }
  },

  // 获取手机号
  getPhoneNumber(e) {
    console.log('授权返回信息', e)
    const { code, encryptedData, iv, errMsg, errno } = e.detail
    if (errMsg !== 'getPhoneNumber:ok')
      return Toast({
        context: this,
        selector: '#t-toast',
        message: errMsg
      })

    var param = {
      encryptedData,
      iv,
      code: this.data.code,
      phonecode: code
    }
    //发起请求获取手机号
    wx.request({
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      url: this.data.apiUrl + '/api/login/codeGetOpenid',
      data: param,
      dataType: 'json',
      success: (response) => {
        var res = response.data
        if (res.code == 0) {
          console.log('登录返回信息', res)
          //可以把token和用户信息保存到本地缓存，前后端携带token交互
          // 把用户信息缓存到本地
          let { avatar, nickname, token, openid, mobile } = res.data
          if (!mobile) {
            wx.showToast({
              title: '授权失败',
              icon: 'error',
              duration: 1000
            })
            this.setData({
              isShowquan: false
            })
            return
          }
          mobile = util.encryptPhoneNumber(mobile)
          const nameInfoObject = {
            avatarUrl: avatar,
            nickName: nickname,
            mobile
          }
          wx.setStorageSync('user', res.data)
          wx.setStorageSync('openid', openid)
          wx.setStorageSync('nameInfoObject', nameInfoObject)
          wx.setStorageSync('token', token)
          this.setData({
            token: token
          })

          this.getAddressList()

          // 信息存储完成后返回我的页面
          wx.switchTab({
            url: '/pages/home/index',
            success: function (e) {
              const page = getCurrentPages().pop()
              console.log(page)
              if (page == undefined || page == null) return
              page.onLoad()
              page.onReady()
            }
          })
        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'error',
            duration: 1000
          })
          this.setData({
            isShowquan: false
          })
        }
      }
    })
  },

  //切换登录方式
  onIconTap(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      loginType: type
    })
  },
  agreeTap(e) {
    this.setData({
      argee: !this.data.argee
    })
  },
  handleAgree() {
    if (!this.data.argee) {
      wx.showModal({
        title: '温馨提示',
        content: '请先阅读并同意隐私协议和用户协议',
        cancelText: '不同意',
        confirmText: '同意',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              argee: true
            })
          }
        }
      })
    }
  }
})
